package com.copyctrl.admin.service.impl;

import cn.hutool.json.JSONUtil;
import com.copyctrl.admin.service.UserService;
import com.copyctrl.campus.common.constant.RedisConstant;
import com.copyctrl.campus.common.domain.Message;
import com.copyctrl.mapper.CampUserMapper;
import com.copyctrl.model.CampUser;
import com.copyctrl.model.CampUserExample;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author:JH
 * @version:1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    CampUserMapper mapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public List<CampUser> findAll() {
        CampUserExample example = new CampUserExample();
        example.createCriteria().andIdIsNotNull();
        return mapper.selectByExample(example);
    }

    @Override
    public int sendMessage(String message, String ToUserId) throws IOException {
        return sendMessageTo(message, ToUserId,"4");
    }

    public int sendMessageTo(String message, String ToUserId, String type) throws IOException {
        //系统推送
        Message m = new Message();
        m.setMessage(message);
        m.setFromId("1");
        m.setToId(ToUserId);
        m.setMessageType(type);
        m.setTime(new Date());
        if (type.equals("4")) {
            //存入聊天记录里
            Integer i1 = new Integer("0");
            Integer i2 = new Integer(ToUserId);
            String key = "";
            if (i1 > i2) {
                key = ToUserId + "0";
            } else {
                key = "0" + ToUserId;
            }
            redisTemplate.opsForZSet().add(RedisConstant.MESSAGE_ALL + key, JSONUtil.toJsonStr(m), System.currentTimeMillis());
        }
        //把消息存入redis中（未读key）判断类型，仅存type为4的消息
        if (m.getMessageType() == "4") {
            long score = System.currentTimeMillis();
            redisTemplate.opsForZSet().add(RedisConstant.MESSAGE_USER_NOT_READ + m.getToId(), JSONUtil.toJsonStr(m), score);
        }
        return 1;
    }
}
